package hz.mobileproject.pda.toolsmanager.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.entity.response.Rp_loadPrisonerInfo;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsRetrieveAlreadyLVAdaper;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsRetrieveWaitLVAdaper;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsStockAdapter;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_ModifyToolStatus;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_FreeCountTools;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_StationInfo;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolInfo;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolSysSet;
import hz.mobileproject.pda.toolsmanager.utils.ToolCommonHttpUtils;
import hz.mobileproject.pda.ui.base.BaseScanActivity;
import hz.mobileproject.pda.utils.HttpRqUtils;

/**
 * 工具收回
 */
@ContentView(R.layout.activity_tools_retrieve)
public class ToolsRetrieveActivity extends BaseScanActivity implements ToolsRetrieveAlreadyLVAdaper.OnDeleteClickListener {
    @ViewInject(R.id.lv_tools_retrieve_wait)
    private ListView lv_tools_retrieve_wait;
    @ViewInject(R.id.lv_tools_retrieve_already)
    private ListView lv_tools_retrieve_already;
    @ViewInject(R.id.lv_tools_stock)
    private ListView lv_tools_stock;
    @ViewInject(R.id.tv_prisonerName)
    private TextView tv_prisonerName;
    @ViewInject(R.id.tv_workPosition)
    private TextView tv_workPosition;

    private Gson mGson;
    private ToolsRetrieveWaitLVAdaper mWaitLVAdaper;
    private ToolsRetrieveAlreadyLVAdaper mAlreadyLVAdaper;
    private ToolsStockAdapter mToolsStockAdapter;
    private RP_ToolSysSet mToolSystemSet;
    //当前民警信息
    private Response_loadPoliceInfo mPoliceInfo;
    //当前扫码罪犯
    private Rp_loadPrisonerInfo mPrisoner;
    //当前扫描工位
    private RP_StationInfo mStation;

    private static final int REQUEST_CODE_POLICE = 0x1011;
    private static final int REQUEST_CODE_PRISONER = 0x1012;
    private static final int REQUEST_CODE_WORK_POSITION = 0x1013;
    private static final int REQUEST_CODE_TOOLS = 0x1014;

    @Override
    protected void initData() {
        setTitleText("工具收回");
        mGson = new Gson();
        mWaitLVAdaper = new ToolsRetrieveWaitLVAdaper(this, new ArrayList<RP_ToolInfo>());
        lv_tools_retrieve_wait.setAdapter(mWaitLVAdaper);
        mAlreadyLVAdaper = new ToolsRetrieveAlreadyLVAdaper(this, new ArrayList<RP_ToolInfo>());
        lv_tools_retrieve_already.setAdapter(mAlreadyLVAdaper.setOnDeleteClickListener(this));
        mToolsStockAdapter = new ToolsStockAdapter(this, new ArrayList<RP_FreeCountTools>());
        lv_tools_stock.setAdapter(mToolsStockAdapter);

        mToolSystemSet = (RP_ToolSysSet) getIntent().getSerializableExtra("key");
        //扫描民警
        scanPolice();
    }

    @Override
    protected void onScanSucesess(int requestCode, String scanMsg) {
        LogUtils.e(scanMsg);
        switch (requestCode) {
            case REQUEST_CODE_POLICE:
                getPliceInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_PRISONER:
                getPrisonerInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_WORK_POSITION:
                getWorkPositionInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_TOOLS:
                changeToolsStatus(scanMsg);
                break;
        }
    }

    @Event({R.id.btn_tools_retrieve_next, R.id.btn_tools_retrieve_complete})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.btn_tools_retrieve_next:
                modifyToolStatus(R.id.btn_tools_grant_next);
                break;
            case R.id.btn_tools_retrieve_complete:
                modifyToolStatus(R.id.btn_tools_grant_complete);
                break;
        }
    }


    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getPoliceInfoFromSer(scanStr, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
                if (loadPoliceInfo == null) {
                    ToastUtils.showLong("民警信息为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mPoliceInfo = loadPoliceInfo;
                setTitleText(mPoliceInfo.getPolice_name());
                //获取库存信息
                getFreeToolsCountFromSer();
                //打开扫描
                scanAfterPolice();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取民警信息失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取民警信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取库存信息
     */
    private void getFreeToolsCountFromSer() {
        ToolCommonHttpUtils.getFreeToolsCountFromSer(mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                List<RP_FreeCountTools> tempList = mGson.fromJson(data, new TypeToken<ArrayList<RP_FreeCountTools>>() {
                }.getType());
                mToolsStockAdapter.clearAdd(tempList);
                if (tempList == null || tempList.size() == 0) {
                    ToastUtils.showLong("库存信息为空");
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取库存信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取库存信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取罪犯信息
     *
     * @param scanStr
     */
    private void getPrisonerInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getPrisonerInfoFromSer(scanStr, mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                Rp_loadPrisonerInfo loadPrisonerInfo = mGson.fromJson(data, Rp_loadPrisonerInfo.class);
                if (loadPrisonerInfo == null) {
                    ToastUtils.showLong("罪犯信息为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mPrisoner = loadPrisonerInfo;
                tv_prisonerName.setText(mPrisoner.getPrisoner_name());
                scanAfterPrison();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取罪犯信息失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取罪犯信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取工位信息
     *
     * @param scanStr
     */
    private void getWorkPositionInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getWorkStationInfoFromSer(scanStr, mToolSystemSet, mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                RP_StationInfo station = mGson.fromJson(data, RP_StationInfo.class);
                if (station == null) {
                    ToastUtils.showLong("工位信息格式错误或为空");
                    return;
                }
                mStation = station;
                tv_workPosition.setText(station.getStation_name());

                scanAfterWorkStation();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取工位信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取工位信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 调取接口获取已发放列表
     */
    private void getGrantedToolsList() {
        ToolCommonHttpUtils.getGrantedToolsList(mToolSystemSet, mPoliceInfo, mPrisoner, mStation, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                List<RP_ToolInfo> toolInfoList = mGson.fromJson(data, new TypeToken<ArrayList<RP_ToolInfo>>() {
                }.getType());
                mWaitLVAdaper.clearAdd(toolInfoList);
                if (toolInfoList == null || toolInfoList.size() == 0) {
                    ToastUtils.showLong("没有已发放的工具");
                    mScanLoadingDialog.dismiss();
                    scanAfterPolice();
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取已发放列表失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取已发放列表失败");
                LogUtils.e(ex.toString());
            }
        });
    }

    /**
     * 将待回收放入已回收
     *
     * @param scanMsg
     */
    private void changeToolsStatus(String scanMsg) {
        scanMsg = scanMsg.indexOf(mToolSystemSet.getToolPrefix()) == 0 ? scanMsg.substring(2) : scanMsg;
        for (int i = mWaitLVAdaper.getCount() - 1; i >= 0; i--) {
            RP_ToolInfo item = mWaitLVAdaper.getItem(i);
            if (scanMsg.equals(item.getTool_id())) {
                mWaitLVAdaper.deleteOne(i);
                mAlreadyLVAdaper.add(0, item);
                return;
            }
        }
        ToastUtils.showLong("扫描工具不存在待回收列表");
    }

    /**
     * 将已回收放入待回收
     *
     * @param position
     */
    @Override
    public void onAlreadyLvDeleteClick(final int position) {
        new AlertDialog.Builder(this).setTitle("提示")
                .setMessage("是否取消收回此工具？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        RP_ToolInfo item = mAlreadyLVAdaper.getItem(position);
                        mAlreadyLVAdaper.deleteOne(position);
                        mWaitLVAdaper.add(0, item);
                    }
                }).create().show();
    }

    /**
     * 请求网络接口提交发放
     */
    private void modifyToolStatus(final int viewID) {
        if (mPoliceInfo == null) {
            ToastUtils.showLong("请先获取民警信息");
            return;
        }
        switch (mToolSystemSet.getGive_object()) {
            case RP_ToolSysSet.TSS_GIVE_OBJECT_WORKPOSITION:
                if (mStation == null) {
                    ToastUtils.showLong("请先获取工位信息");
                    return;
                }
                break;
            case RP_ToolSysSet.TSS_GIVE_OBJECT_PERSON:
                if (mPrisoner == null) {
                    ToastUtils.showLong("请先获取使用人信息");
                    return;
                }
                break;
            case RP_ToolSysSet.TSS_GIVE_OBJECT_WORKPOSITION_PERSON:
                if (mStation == null) {
                    ToastUtils.showLong("请先获取工位信息");
                    return;
                }
                if (mPrisoner == null) {
                    ToastUtils.showLong("请先获取使用人信息");
                    return;
                }
                break;
        }
        if (mAlreadyLVAdaper.getCount() <= 0) {
            ToastUtils.showLong("请扫描回收工具");
            return;
        }
        List<RQ_ModifyToolStatus> modifyToolStatusList = new ArrayList<>();
        for (int i = 0; i < mAlreadyLVAdaper.getCount(); i++) {
            RP_ToolInfo item = mAlreadyLVAdaper.getItem(i);

            RQ_ModifyToolStatus modifyToolStatus = new RQ_ModifyToolStatus();
            modifyToolStatus.setCus_number(mPoliceInfo.getCus_number());
            modifyToolStatus.setDprt_id(mPoliceInfo.getDepartment_id());
            modifyToolStatus.setDprt_name(mPoliceInfo.getDepartment_name());
            modifyToolStatus.setManage_person_id(mPoliceInfo.getPolice_id());
            modifyToolStatus.setManage_person_name(mPoliceInfo.getPolice_name());
            if (mStation != null) {
                modifyToolStatus.setStation_id(mStation.getStation_id());
                modifyToolStatus.setStation_name(mStation.getStation_name());
            }
            if (mPrisoner != null) {
                modifyToolStatus.setUse_person_id(mPrisoner.getPrisoner_id());
                modifyToolStatus.setUse_person_name(mPrisoner.getPrisoner_name());
            }
            modifyToolStatus.setType(RQ_ModifyToolStatus.TYPE_RETRIEVE);
            modifyToolStatus.setTool_id(item.getTool_id());
            modifyToolStatus.setTool_name(item.getTool_name());
            modifyToolStatus.setTool_type(item.getTool_type()+"");
            modifyToolStatus.setSf_status(RP_ToolInfo.SF_STATUS_FREE);

            modifyToolStatusList.add(modifyToolStatus);
        }

        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_MODIFY_TOOL_STATUS, modifyToolStatusList, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                switch (viewID) {
                    case R.id.btn_tools_grant_next:
                        ToastUtils.showLong("回收提交成功");
                        //TODO 清空本页面的信息
                        tv_prisonerName.setText("");
                        mPrisoner = null;
                        tv_workPosition.setText("");
                        mStation = null;
                        mWaitLVAdaper.deleteAll();
                        mAlreadyLVAdaper.deleteAll();
                        scanAfterPolice();
                        //重新获取库存
                        getFreeToolsCountFromSer();
                        break;
                    case R.id.btn_tools_grant_complete:
                        new AlertDialog.Builder(ToolsRetrieveActivity.this).setTitle("提示")
                                .setMessage("回收提交成功，本页面将关闭")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        ToolsRetrieveActivity.this.finish();
                                    }
                                }).setCancelable(false).create().show();
                        break;
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("回收提交失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("回收提交失败");
                LogUtils.e(ex);
            }
        });
    }

    /**
     * ====================================扫描流程=========================================
     */
    private void scanPolice() {
        //是否需要扫描民警
        if (RP_ToolSysSet.TSS_CALL_TYPE_SCAN_USER == (mToolSystemSet.getCall_type())) {
            //扫民警
            openScan(REQUEST_CODE_POLICE, mToolSystemSet, "请扫描民警条码");
        } else if (RP_ToolSysSet.TSS_CALL_TYPE_LOGIN_USER == (mToolSystemSet.getCall_type())) {
            //使用登录民警信息
            mPoliceInfo = new Response_loadPoliceInfo();
            Response_login_user loginUser = MainApp.getInstance().getLoginUser();
            mPoliceInfo.setCus_number(loginUser.getCus_number());
            mPoliceInfo.setDepartment_id(loginUser.getDepartment_id());
            mPoliceInfo.setDepartment_name(loginUser.getDepartment_name());
            mPoliceInfo.setPolice_code(loginUser.getPolice_code());
            mPoliceInfo.setPolice_id(loginUser.getPolice_id());
            mPoliceInfo.setPolice_name(loginUser.getPolice_name());
            //接着扫描
            scanAfterPolice();
        }
    }

    private void scanAfterPolice() {
        //判断工具发放绑定方式
        switch (mToolSystemSet.getGive_object()) {
            case RP_ToolSysSet.TSS_GIVE_OBJECT_WORKPOSITION:
                //扫描扫描工位
                openScan(REQUEST_CODE_WORK_POSITION, mToolSystemSet, "请扫描工位");
                break;
            case RP_ToolSysSet.TSS_GIVE_OBJECT_PERSON:
            case RP_ToolSysSet.TSS_GIVE_OBJECT_WORKPOSITION_PERSON:
                //扫描使用人
                openScan(REQUEST_CODE_PRISONER, mToolSystemSet, "请扫描使用人");
                break;
        }
    }

    private void scanAfterPrison() {
        //判断工具发放绑定方式
        switch (mToolSystemSet.getGive_object()) {
            case RP_ToolSysSet.TSS_GIVE_OBJECT_PERSON:
                //请扫描工具
                scanTools();
                break;
            case RP_ToolSysSet.TSS_GIVE_OBJECT_WORKPOSITION:
            case RP_ToolSysSet.TSS_GIVE_OBJECT_WORKPOSITION_PERSON:
                //扫描扫描工位
                openScan(REQUEST_CODE_WORK_POSITION, mToolSystemSet, "请扫描工位");
                break;
        }
    }

    private void scanAfterWorkStation() {
        scanTools();
    }

    private void scanTools() {
        //获取已发放工具列表
        getGrantedToolsList();
        //请扫描工具
        openScan(REQUEST_CODE_TOOLS, mToolSystemSet, "请扫描工具");

        if (RP_ToolSysSet.TSS_SWEEP_TYPE_CAMERA == (mToolSystemSet.getSweep_type())) {
            setTitleRightIcon(true, R.mipmap.scan_camera);
            getIv_title_right().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //请扫描工具
                    openScan(REQUEST_CODE_TOOLS, mToolSystemSet, "请扫描工具");
                }
            });
        }
    }

}
